package main.java.com.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import main.java.com.domain.User;
import main.java.com.util.ConnDb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Anti-fake label
 * <p>
 * ClassName: QueryDicAction
 * Package: main.java.com.action
 * <p>
 * ！！！个人电子防伪标识！！！
 * <p>
 * Description:
 *
 * @Author 22软件6班 陈彬
 * @Create 2023/12/20 8:58
 * @Version 1.0
 */
@WebServlet("/QueryDicServlet")
public class QueryDicAction extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //配置请求和响应的字符集为UTF-8
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //根据dic参数判断查询的是哪个页面的数据字典表
        String dic=request.getParameter("dic");
        //创建一个jsonobject对象
        JSONObject jsonObject=new JSONObject();
        if ("1".equals(dic)){
            //获取参数
            String professionId=request.getParameter("professionId");
            //调用查询班级信息方法
            List<HashMap> list=this.queryDicClass(professionId);
            jsonObject.put("list",list);
        }
        //将jsonobject转化为字符串
        String json=JSON.toJSONString(jsonObject);
        //将json字符串写入响应信息中
        response.getWriter().write(json);
    }
    //根据账号和密码查询信息
    public  List<HashMap> queryDicClass(String professionId){
        List<HashMap> list=new ArrayList<>();
        try{
            //调用连接数据库方法
            ConnDb db=new ConnDb();
            Connection conn=db.dataBaseConnectionTest();
            //构建sql
            String sql="SELECT * from tb_dic_class WHERE professionId="+professionId;
            //利用PreparedStatement预处理接口创建对象pstm
            PreparedStatement pstm=conn.prepareStatement(sql);
            //执行方法
            ResultSet rs=pstm.executeQuery();
            while (rs.next()){//如果由查询到数据，则进入while循环
                HashMap map=new HashMap(12);
                map.put("id",rs.getInt("id"));
                map.put("name",rs.getString("name"));
                list.add(map);
            }
            conn.close();//关闭数据
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
}
